const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../../common/bee/bee')

// 为角色分配对应菜单
router.post('/role-menu', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { role_id, menu_id } = req.body
  if (
    !Bee.StringUtils.isNumber(role_id) ||
    !Bee.StringUtils.isNotBlank(menu_id)
  )
    return handleError(10003, '参数错误')

  // 将得到的参数 , 分割为数组
  // 处理多条数据
  let midArr = menu_id.split(',')
  let dataArr = [] // 要批量插入的数据
  midArr.forEach((item) => {
    dataArr.push([role_id, parseInt(item)])
  })

  // 查询是否有该角色和菜单
  const [findRoleAndMenuError, RoleAndMenu] = await to(
    db.query(
      'SELECT r.id role_id, m.id menu_id FROM role r, menu m WHERE r.id=? AND m.id IN (?)',
      [role_id, midArr]
    )
  )
  if (
    findRoleAndMenuError ||
    !RoleAndMenu ||
    RoleAndMenu.length !== midArr.length
  )
    return handleError(-1, findRoleAndMenuError)

  // 查询该角色是否已有该菜单
  const [findRoleMenuError, RoleMenuList] = await to(
    db.query('SELECT * FROM role_menu WHERE role_id=? AND menu_id IN (?);', [
      role_id,
      midArr,
    ])
  )

  // 如果查询有数据代表已经有该菜单 不允许再分配已有的菜单
  if (findRoleMenuError || !RoleMenuList || RoleMenuList.length > 0)
    return handleError(-1, findRoleMenuError)

  const [insertRoleMenuError, insertRoleMenuSuccess] = await to(
    db.query('INSERT INTO role_menu (role_id, menu_id) VALUES ?', [dataArr])
  )
  if (
    insertRoleMenuError ||
    !insertRoleMenuSuccess ||
    insertRoleMenuSuccess.affectedRows === 0
  )
    return handleError(-1, insertRoleMenuError)

  return resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
